/**
 * URL处理工具函数
 */

/**
 * 解析URL查询参数
 * @param url URL字符串，默认为当前页面URL
 * @returns 查询参数对象
 */
export function parseQuery(url?: string): Record<string, string> {
  const query: Record<string, string> = {}
  const urlStr = url || window.location.href
  const queryStr = urlStr.split('?')[1]
  
  if (!queryStr) return query
  
  const pairs = queryStr.split('&')
  
  for (const pair of pairs) {
    const [key, value] = pair.split('=')
    if (key) {
      query[decodeURIComponent(key)] = decodeURIComponent(value || '')
    }
  }
  
  return query
}

/**
 * 构建URL查询字符串
 * @param params 参数对象
 * @returns 查询字符串，不包含问号
 */
export function buildQuery(params: Record<string, any>): string {
  const parts: string[] = []
  
  for (const key in params) {
    if (Object.prototype.hasOwnProperty.call(params, key)) {
      const value = params[key]
      if (value !== undefined && value !== null) {
        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      }
    }
  }
  
  return parts.join('&')
}

/**
 * 向URL添加查询参数
 * @param url 基础URL
 * @param params 要添加的参数对象
 * @returns 添加参数后的URL
 */
export function addQueryParams(url: string, params: Record<string, any>): string {
  if (!params || Object.keys(params).length === 0) return url
  
  const queryString = buildQuery(params)
  if (!queryString) return url
  
  const separator = url.includes('?') ? '&' : '?'
  return `${url}${separator}${queryString}`
}

/**
 * 从URL中获取指定参数值
 * @param name 参数名
 * @param url URL字符串，默认为当前页面URL
 * @returns 参数值，不存在则返回null
 */
export function getQueryParam(name: string, url?: string): string | null {
  const params = parseQuery(url)
  return params[name] || null
}

/**
 * 更新URL查询参数
 * @param params 要更新的参数对象
 * @param url URL字符串，默认为当前页面URL
 * @returns 更新参数后的URL
 */
export function updateQueryParams(params: Record<string, any>, url?: string): string {
  const urlStr = url || window.location.href
  const [baseUrl, queryStr] = urlStr.split('?')
  
  const currentParams = queryStr ? parseQuery(urlStr) : {}
  const newParams = { ...currentParams, ...params }
  
  // 移除值为null或undefined的参数
  Object.keys(newParams).forEach(key => {
    if (newParams[key] === null || newParams[key] === undefined) {
      delete newParams[key]
    }
  })
  
  const newQueryStr = buildQuery(newParams)
  return newQueryStr ? `${baseUrl}?${newQueryStr}` : baseUrl
}

/**
 * 从URL中移除指定参数
 * @param names 要移除的参数名数组
 * @param url URL字符串，默认为当前页面URL
 * @returns 移除参数后的URL
 */
export function removeQueryParams(names: string[], url?: string): string {
  const urlStr = url || window.location.href
  const [baseUrl, queryStr] = urlStr.split('?')
  
  if (!queryStr) return urlStr
  
  const params = parseQuery(urlStr)
  
  for (const name of names) {
    delete params[name]
  }
  
  const newQueryStr = buildQuery(params)
  return newQueryStr ? `${baseUrl}?${newQueryStr}` : baseUrl
}

/**
 * 判断URL是否为绝对URL
 * @param url URL字符串
 * @returns 是否为绝对URL
 */
export function isAbsoluteUrl(url: string): boolean {
  return /^(?:[a-z]+:)?\/\//i.test(url)
}

/**
 * 拼接URL路径
 * @param base 基础URL
 * @param path 路径
 * @returns 拼接后的URL
 */
export function joinUrl(base: string, path: string): string {
  if (!base) return path
  if (!path) return base
  
  const baseEndsWithSlash = base.endsWith('/')
  const pathStartsWithSlash = path.startsWith('/')
  
  if (baseEndsWithSlash && pathStartsWithSlash) {
    return base + path.substring(1)
  }
  
  if (!baseEndsWithSlash && !pathStartsWithSlash) {
    return `${base}/${path}`
  }
  
  return base + path
}